package com.dht.imagepicker.albums

import android.app.Application
import android.content.ContentUris
import android.os.Build
import android.provider.MediaStore
import androidx.core.database.getIntOrNull
import androidx.core.database.getLongOrNull
import androidx.core.database.getStringOrNull
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.dht.imagepicker.ImageInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class AlbumsViewModel(application: Application) : AndroidViewModel(application) {

    val imageInfoMutableLiveData: MutableLiveData<MutableList<ImageInfo>> = MutableLiveData()

    fun fetchImages() {

        viewModelScope.launch(Dispatchers.IO) {

            val projection = arrayOf(
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.BUCKET_ID,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
            )

//            val imageCollectionUri = ImageHelper.getImageCollectionUri()
//            val sortBy = when (config.imageSort.by) {
//                SortBy.DISPLAY_NAME -> MediaStore.Images.Media.DISPLAY_NAME
//                SortBy.DATE_MODIFIED -> MediaStore.Images.Media.DATE_MODIFIED
//                else -> MediaStore.Images.Media.DATE_ADDED
//            }
//            val sortOrder = when (config.imageSort.order) {
//                SortOrder.DESC -> "DESC"
//                else -> "ASC"
//            }
            val contentUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
            } else {
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            }

            getApplication<Application>().contentResolver.query(
                contentUri,
                projection,
                null,
                null,
                ""
            )?.let { cursor ->

                try {
                    val imageInfos = arrayListOf<ImageInfo>()
                    val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
                    val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                    val dateAddColumn =
                        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)

                    val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)

                    val displayNameColumn =
                        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
                    val bucketIdColumn =
                        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_ID)
                    val bucketDisplayNameColumn =
                        cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)

                    while (cursor.moveToNext()) {

                        val id = cursor.getLongOrNull(idColumn) ?: 0
                        val data = cursor.getStringOrNull(dataColumn) ?: ""
                        val dateAdd = cursor.getLongOrNull(dateAddColumn) ?: 0
                        val size = cursor.getIntOrNull(sizeColumn) ?: 0
                        val displayName = cursor.getStringOrNull(displayNameColumn) ?: ""
                        val bucketId = cursor.getIntOrNull(bucketIdColumn) ?: 0
                        val bucketDisplayName =
                            cursor.getStringOrNull(bucketDisplayNameColumn) ?: ""

                        val uri = ContentUris.withAppendedId(contentUri, id)

                        val info =
                            ImageInfo(uri, data, displayName, bucketDisplayName, dateAdd, size)

                        imageInfos.add(info)
                    }
                    withContext(Dispatchers.Main) {
                        imageInfoMutableLiveData.value = imageInfos
                    }
                } catch (e: Exception) {
                    e.printStackTrace()

                    withContext(Dispatchers.Main) {
                        imageInfoMutableLiveData.value = mutableListOf()
                    }
                }

                cursor.close()
            }
        }
    }

}